<?php


namespace App\GatewayWorker;

use App\Models\UserChat;
use App\Models\UserLikeImage;
use App\Models\WxUser;
use App\Tools\JwtTools;
use Elasticsearch\Endpoints\License\Post;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;


class Events
{
    public static function onWorkerStart($businessWorker) //开启成功的提示
    {
        echo "BusinessWorker    Start\n";
    }

    public static function onConnect($client_id) //连接成功事件
    {

        Gateway::sendToClient($client_id, json_encode(['type' => 'init', 'client_id' => $client_id],256));

    }

    public static function onWebSocketConnect($client_id, $data)
    {
//        Gateway::sendToClient($client_id, json_encode(['type' => 'init', 'client_id' => $client_id]));
    }

    public static function onMessage($client_id, $message)
    {
        $message = json_decode($message,true);//后端的消息
        switch ($message['type']){
            case "init":
                $uid = JwtTools::transitionId($message['token']);//当前用户id
                $data = \App\Models\UserChat::where('send_id',$message['to_id'])->where('receive_id',$uid)->where('send_status',0)->get()->toArray();
                foreach ($data as &$v){//获取到当前用户没有读的消息
                    UserChat::where('id',$v['id'])->update([
                        'send_status'=>1
                    ]);
                    $v['send_status']=1;
                }
                $userImage = UserLikeImage::where('uid',$uid)->get();//获取到用户收藏的表情
                Gateway::bindUid($client_id,$uid);//绑定当前的fd至用户id
                Gateway::sendToUid($message['to_id'],json_encode(['data'=>$data,'type'=>"text"],256));//将消息发送回去
                Gateway::sendToUid($uid,json_encode(['data'=>$data,'type'=>"text"],256));//将消息发送回去
                Gateway::sendToUid($uid,json_encode(['data'=>$userImage,'type'=>"image"],256));//查询到的表情发送回去
                break;
            case "list":
                $uid = $message['uid'];//当前用户的id
                Gateway::bindUid($client_id,$uid);//绑定
                $data = \App\Models\UserChat::where('receive_id',$uid)->get()->toArray();
                $data= array_column($data,'send_id');
                $data=array_unique($data);//查询到的消息去重id
                $user = \App\Models\WxUser::whereIn('id',$data)->get()->toArray();
                if(count($user)!=1){
                    foreach ($user as &$value){
                        $value['content']=\App\Models\UserChat::where('send_id',$value['id'])->orderby('created_at',"desc")->limit(1)->get();
                    }
                }else{
                    $user['content'] = \App\Models\UserChat::where('send_id',$user[0]['id'])->orderby('created_at',"desc")->limit(1)->get();
                }
                Gateway::sendToUid($uid,json_encode(['data'=>$user,'type'=>"lists"]));
                break;
            case "text":
                $uid = JwtTools::transitionId($message['token']);//当前用户ID
                $toId = $message['uid'];//当前发送的id
                $toUser = Gateway::isUidOnline($toId);
                $data=[
                    "send_id"=>$uid,
                    "receive_id"=>$toId,
                    "send_content"=>$message['content'],
                    "send_status"=>1//已读
                ];
                $user = \App\Models\WxUser::where('id',$uid)->get()->toArray();
                foreach ($user as &$value){
                    $value['content']=\App\Models\UserChat::where('send_id',$value['id'])->orderby('created_at',"desc")->limit(1)->get();
                }
                Gateway::sendToUid($toId,json_encode(['data'=>$user,'type'=>"lists"],256));
                if($toUser){
                    $userModel = UserChat::create($data);
                    Gateway::sendToUid($toId,json_encode(['data'=>$userModel,'type'=>"text"],256));
                    Gateway::sendToUid($uid,json_encode(['data'=>$userModel,'type'=>"text"],256));
                    break;
                }else{
                    $data['send_status']=0;
                    $userModel = UserChat::create($data);
                    print_r(1);
                  //  Gateway::sendToUid($toId,json_encode(['data'=>$userModel,'type'=>"text"],256));
                    Gateway::sendToUid($uid,json_encode(['data'=>$userModel,'type'=>"send_status",'id'=>$userModel->id],256));
                    break;
                }
                break;
            case "image":
                $uid = JwtTools::transitionId($message['token']);//当前用户ID
                $toId = $message['uid'];//当前发送的id
                $toUser = Gateway::isUidOnline($toId);
                $userImage= UserLikeImage::where('uid',$uid)->where('id',$message['id'])->first();
                $userImage="<img src=".$userImage['image']." style=max-width:100%;height:auto;>";
                $data=[
                    "send_id"=>$uid,
                    "receive_id"=>$toId,
                    "send_content"=>$userImage,
                    "send_status"=>1//已读
                ];
                $user = \App\Models\WxUser::where('id',$uid)->get()->toArray();
                foreach ($user as &$value){
                    $value['content']=\App\Models\UserChat::where('send_id',$value['id'])->orderby('created_at',"desc")->limit(1)->get();
                }
                Gateway::sendToUid($toId,json_encode(['data'=>$user,'type'=>"lists"],256));
                if($toUser){
                    $userModel = UserChat::create($data);
                    Gateway::sendToUid($toId,json_encode(['data'=>$userModel,'type'=>"text"],256));
                    Gateway::sendToUid($uid,json_encode(['data'=>$userModel,'type'=>"text"],256));
                    break;
                }else{
                    $data['send_status']=0;
                    $userModel = UserChat::create($data);
                    print_r(1);
                    //  Gateway::sendToUid($toId,json_encode(['data'=>$userModel,'type'=>"text"],256));
                    Gateway::sendToUid($uid,json_encode(['data'=>$userModel,'type'=>"send_status",'id'=>$userModel->id],256));
                    break;
                }
                break;
        }
//        $from_uid = $message->from_uid;
//        $to_uid = $message->to_uid;;
//        switch ($message->mode) {
//            case 'say':   #处理发送的聊天
//
//                $response['data'] = "";
//                if (Gateway::isUidOnline($to_uid)) {
//                    $response['msg'] = '已发送至uid为：' . $to_uid;
//                    Gateway::sendToUid($to_uid, json_encode($response));
//                } else {
//                    $response['msg'] = '对方不在线';
//                }
//                break;
//            case 'chats':  #获取聊天列表
//               // $chats = Chat::where('from_id', $message->from_id)->get();
//                $response['data'] = ['chats' => ""];
//                break;
//            default:
//                $response['status'] = 201;
//                $response['msg'] = 'Undefined';
//        }

       // Gateway::sendToClient($client_id, json_encode($response));
    }

    public static function onClose($client_id)
    {
        print_r(1);
        Gateway::sendToClient($client_id,json_encode(['data'=>'客户端已断开链接','type'=>"close"],256));
    }

}
